var express = require('express');
var router = express.Router();
const shsDB = require("../../db/index.js");
const {
	comSensitiveWords
} = require("./../../utils/sensitive.js");
// 敏感词对象
let mgcWordObj = {
	value: [], // 初始化为空数组，避免未定义错误
	code: "sensitiveWords",
	time: new Date().getTime() - 1 // 初始化为过去时间，确保首次请求时更新敏感词
};

router.post('/add', jwtVerify, async function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let item = req.body;
		if ((!item.content && !item.images) || item.Visibility == undefined || item.stateTags ==
			undefined) {
			obj.message = "参数不合法";
			res.send(JSON.stringify(obj))
			return
		}
		if (item.content != "") {
			try {
				let result = await comSensitiveWords(item.content);
				if (result.status && result.code == 200) {
					res.send(JSON.stringify({
						...result,
						code: 201,
						message: "存在敏感词，请修改后再发布"
					}));
					return;
				} else if (result.code == 500) {
					throw new Error("detect Sensitive word error.");
				}
				if (!item.images) {
					senState(res, userinfo, item, status = 1, message = "发布成功");
				} else {
					senState(res, userinfo, item);
				}
			} catch (error) {
				throw new Error("Internal Server Error.");
			}
		} else {
			senState(res, userinfo, item);
		}
	} catch (e) {
		res.send(JSON.stringify({
			status: false,
			highlightedText: "",
			code: 500,
			message: "服务器内部错误 Internal Server Error",
			error: e.message
		}));
	}
})
/** 必要参数：res, userinfo； item； status 状态 1启用0禁用 3待审核4未通过5删除；message提示*/
function senState(res, userinfo, item, status = 3, message = "审核中[如需加急请联系2192555809@qq.com]") {
	try {
		let sql =
			`INSERT INTO \`imdb\`.\`statecontent\`
		(\`stateId\`, \`fromId\`, \`fromUrl\`, \`fromUsername\`, \`content\`, \`images\`, \`tags\`, \`Visibility\`,\`hot\`,\`status\`, \`createTime\`, \`updateTime\`) 
		VALUES (null, '${userinfo.fromId}', '${userinfo.fromUrl}', '${userinfo.fromName}', ?, ?, ?, ${item.Visibility},1,?, '${getdate()}', '${getdate()}');`
		shsDB(sql, [item.content, item.images, item.stateTags, status]).then(data => {
				if (data.insertId) {
					let sqlData = `INSERT INTO \`imdb\`.\`statedata\`(\`stateId\`, \`like\`, \`unlike\`, \`review\`)
				 VALUES (${data.insertId}, 0,0,0); `
					return shsDB(sqlData);
				}
			}).then(data => {
				res.send(JSON.stringify({
					code: 200,
					message,
					status
				}));
			})
			.catch(err => {
				res.send(JSON.stringify({
					code: 201,
					message: "发布失败 请联系[2192555809@qq.com]" + err.message
				}));
			})
	} catch (error) {
		res.send(JSON.stringify({
			code: 500,
			message: "服务器内部错误" + error.message
		}));
	}
}

//获取动态列表
router.get('/list', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stategetList",
			data: {}
		}
		let item = req.query;
		if (item.pageSize == undefined || item.pageNum == undefined || item.selectValue == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let start = (item.pageNum - 1) * item.pageSize
		let sql = `select * from (select * from statecontent  where Visibility=1 and 
			status=1 ORDER BY createTime desc, hot desc limit ${start},${item.pageSize}) as sc
		left join statedata as sd on sc.stateId=sd.stateId;`
		if (item.selectValue == 3) {
			sql = `select * from (select * from statecontent  where Visibility in (1,2,3) and statecontent.status!=0 and fromId='${userinfo.fromId}' 
		ORDER BY createTime desc, hot desc limit ${start},${item.pageSize}) as sc
	left join statedata as sd on sc.stateId=sd.stateId;`
		}
		if (item.selectValue != 2) {
			shsDB(sql).then(data => {
				obj.code = 200;
				obj.message = "success"
				obj.data = data
				res.send(JSON.stringify(obj))
			}).catch(err => {
				obj.message = err.message
				res.send(JSON.stringify(obj))
			})
		}
		if (item.selectValue == 2) {
			let selectSql =
				`select otherId from relationshipuser as rs where rs.userId='${userinfo.fromId}' and rs.status=1;`
			shsDB(selectSql).then(data => {
				let rsList = []
				if (data.length > 0) {
					for (let i = 0; i < data.length; i++) {
						rsList.push(data[i].otherId)
					}
					let rsFromId = rsList.toString();
					sql = `select * from (select * from statecontent  where Visibility in (1,2) and statecontent.status=1 and 
					fromId in (${rsFromId})
						ORDER BY createTime desc, hot desc limit ${start},${item.pageSize}) as sc
					left join statedata as sd on sc.stateId=sd.stateId;`
					return shsDB(sql);
				}
			}).then(data => {
				obj.code = 200;
				obj.message = "success"
				obj.data = data || [];
				res.send(JSON.stringify(obj))
			}).catch(err => {
				obj.message = err.message
				res.send(JSON.stringify(obj))
			})
		}
	} catch (e) {
		//TODO handle the exception
	}
})
/**
 * 获取指定人物的动态列表
 * @param {string} otherId 要查看用户id
 * @param {string} isres 是否是好友
 * @param {int} pageSize
 * @param {int} pageNum
 */
router.get('/userlist', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "userStategetList",
			data: {}
		}
		let item = req.query;
		if (item.otherId == undefined || item.pageSize == undefined || item.pageNum == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let start = (item.pageNum - 1) * item.pageSize
		//查询是否是好友
		let selectSql =
			`select otherId from relationshipuser as rs where rs.userId='${userinfo.fromId}' and otherId='${item.otherId}' and rs.status=1;`
		shsDB(selectSql).then(res => {
			let Visibility = res ? "1,2" : "1";
			let sql = `select * from (select * from statecontent  where Visibility in (${Visibility}) and 
				status=1 and fromId='${item.otherId}' ORDER BY createTime desc, hot desc limit ${start},${item.pageSize}) as sc
			left join statedata as sd on sc.stateId=sd.stateId;`
			return shsDB(sql);
		}).then(data => {
			obj.code = 200;
			obj.message = "success"
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})
/**
 * 获取指定人物的动态
 * @param {string} stateId 动态ID
 */
router.get('/show', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateShow",
			data: {}
		}
		let item = req.query;
		if (item.stateId == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}

		let sql =
			`select * from (select * from statecontent  where status!=0 and stateId='${item.stateId}' ) as sc left join statedata as sd on sc.stateId=sd.stateId;`
		shsDB(sql).then(data => {
			obj.code = 200;
			obj.message = "success"
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})
//获取热榜
router.get('/hotlist', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stategetHotList",
			data: {}
		}
		let item = req.query;
		if (item.pageSize == undefined || item.pageNum == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let start = (item.pageNum - 1) * item.pageSize
		let sql = `select * from statecontent as sc inner join statedata as sd on sc.stateId=sd.stateId where sc.status=1 and sc.Visibility=1
		ORDER BY sc.hot desc,sd.like desc,sd.review desc limit ${start},${item.pageSize};`
		shsDB(sql).then(res => {
			obj.code = 200;
			obj.message = "success"
			obj.data = res || []
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})
	} catch (e) {
		//TODO handle the exception
	}
})
//点赞
router.post('/like', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateLike",
			data: {}
		}
		let item = req.body;
		if (!item.stateId && !item.code) {
			obj.message = "参数不合法";
			res.send(JSON.stringify(obj))
			return
		}

		let sql =
			`UPDATE \`imdb\`.\`statedata\` SET statedata.like =statedata.like ${item.code} 1 WHERE \`stateId\` = ${item.stateId};`
		shsDB(sql).then(data => {
				obj.code = 200
				obj.message = "success";
				res.send(JSON.stringify(obj))
			})
			.catch(err => {
				obj.message = "点赞失败 请联系[2192555809@qq.com]" + err.message;
				res.send(JSON.stringify(obj))
			})
	} catch (e) {
		//TODO handle the exception
	}
})
//踩
router.post('/unlike', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateLike",
			data: {}
		}
		let item = req.body;
		if (!item.stateId && !item.code) {
			obj.message = "参数不合法";
			res.send(JSON.stringify(obj))
			return
		}

		let sql =
			`UPDATE \`imdb\`.\`statedata\` SET statedata.unlike =statedata.unlike ${item.code} 1 WHERE \`stateId\` = ${item.stateId};`
		shsDB(sql).then(data => {
				obj.code = 200
				obj.message = "success";
				res.send(JSON.stringify(obj))
			})
			.catch(err => {
				obj.message = "操作失败 请联系[2192555809@qq.com]" + err.message;
				res.send(JSON.stringify(obj))
			})
	} catch (e) {
		//TODO handle the exception
	}
})
//删除  状态 1启用0禁用 3待审核4未通过5删除  参数列表 stateIds  数组
router.post('/del', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateLike",
			data: {}
		}
		let item = req.body;
		if (!item.stateIds || item.stateIds.length < 1) {
			obj.message = "参数不合法或参数错误";
			res.send(JSON.stringify(obj))
			return
		}
		let stateIds = item.stateIds.toString()
		let sql = `UPDATE statecontent SET status=5 WHERE stateId in (${stateIds});`

		shsDB(sql).then(data => {
				obj.code = 200
				obj.message = "success";
				res.send(JSON.stringify(obj))
			})
			.catch(err => {
				obj.message = "删除失败 请联系[2192555809@qq.com]" + err.message;
				res.send(JSON.stringify(obj))
			})
	} catch (e) {
		//TODO handle the exception
	}
})


//修改 权限
router.post('/edit', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateLike",
			data: {}
		}
		let item = req.body;
		if (!item.Visibility || !item.stateId) {
			obj.message = "参数不合法或参数错误";
			res.send(JSON.stringify(obj))
			return
		}
		let sql = `UPDATE statecontent SET Visibility='${item.Visibility}' WHERE stateId =${item.stateId};`

		shsDB(sql).then(data => {
				obj.code = 200
				obj.message = "success";
				res.send(JSON.stringify(obj))
			})
			.catch(err => {
				obj.message = "操作失败 请联系[2192555809@qq.com]" + err.message;
				res.send(JSON.stringify(obj))
			})
	} catch (e) {
		//TODO handle the exception
	}
})

//状态封禁  操作者id：fromId  ；被封禁者id:bannedId;备注 remark
router.post("/banned", jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let userinfo = req.shsImUserInfo; //看谁执行的封禁操作

	let obj = {
		code: 201,
		message: "封禁操作",
		status: true
	}

	if (!userinfo.fromId || !bodyItem.bannedId || bodyItem.status == undefined) {
		obj.message = "未按要求传参[fromId,bannedId]";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let remark = "封禁动态"
	let oldStatus = '';
	try {
		oldStatus = bodyItem.status ? 0 : 1;
		if (bodyItem.status) {
			remark = "解除封禁动态"
		}
	} catch (error) {
		//TODO handle the exception
	}
	// 封禁动态表的发布信息
	let stateSql =
		`UPDATE \`imdb\`.\`statecontent\` SET  \`status\` = ${ bodyItem.status},updateTime=now() WHERE \`stateId\` = ${bodyItem.bannedId} and \`status\`=${oldStatus};`
	let controlsSql =
		`INSERT INTO \`imdb\`.\`banned\`(\`id\`, \`controlsID\`, \`bannedId\`, \`remark\`, \`status\`, \`updateTime\`, \`createTime\`)
		 VALUES (null, ${userinfo.fromId}, ${bodyItem.bannedId}, '${remark }', 1, now(), now());`
	shsDB(stateSql).then(data => {
		return shsDB(controlsSql)
	}).then(data => {
		obj.code = 200;
		obj.message = "操作成功"
		res.send(JSON.stringify(obj))
	}).catch(err => {
		obj.code = 201;
		res.send(JSON.stringify(obj))
	})

})

/**
 * 审核动态  列表
 */
router.get('/auditList', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "auditList",
			data: {}
		}
		let item = req.query;
		if (item.pageSize == undefined || item.pageNum == undefined || item.selectValue == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}
		let authoritySql = `select isAdmin from users where Id=${userinfo.fromId} and status=1;`
		shsDB(authoritySql).then(data => {
			if (data && data[0].isAdmin == 1) {
				let start = (item.pageNum - 1) * item.pageSize
				let sql = `select * from (select * from statecontent  where 
					status=${item.selectValue} ORDER BY createTime desc, hot desc limit ${start},${item.pageSize}) as sc
				left join statedata as sd on sc.stateId=sd.stateId;`
				return shsDB(sql)
			}
			obj.message = "您没有权限访问!!!"
			res.send(JSON.stringify(obj))
		}).then(data => {
			obj.code = 200;
			obj.data = data
			obj.message = "操作成功"
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})
/**
 * 审核动态 获取信息展示
 * @param {string} stateId 动态ID
 */
router.get('/auditshow', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "stateShow",
			data: {}
		}
		let item = req.query;
		if (item.stateId == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}

		let sql =
			`select * from (select * from statecontent  where stateId='${item.stateId}' ) as sc left join statedata as sd on sc.stateId=sd.stateId;`
		shsDB(sql).then(data => {
			obj.code = 200;
			obj.message = "success"
			obj.data = data
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})
/**
 * 审核动态
 * @param {string} stateId 动态ID 
 * @param {number} status  状态 4未通过 1通过
 */
router.post('/audit', jwtVerify, function(req, res, next) {
	try {
		let userinfo = req.shsImUserInfo
		let obj = {
			code: 201,
			message: "audit",
			data: {}
		}
		let item = req.body;
		if (item.stateId == undefined || item.status == undefined) {
			obj.message = "参数不合法"
			res.send(JSON.stringify(obj))
			return
		}

		let sql = `update statecontent set status=${item.status} where stateId=${item.stateId};`
		shsDB(sql).then(data => {
			obj.code = 200;
			obj.message = "操作成功"
			res.send(JSON.stringify(obj))
		}).catch(err => {
			obj.message = err.message
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})

module.exports = router;